import type { UploadProps } from "antd";
import { message, Image } from "antd";
import Dragger from "antd/es/upload/Dragger";
import type { ReactElement } from "react";
import { commonService } from "@/api/services/commonService";

import { Iconify } from "../icon";
import { StyledUploadBox, GlobalStyle } from "./styles";

interface Props extends Omit<UploadProps, "action" | "customRequest"> {
	placeholder?: ReactElement;
	value?: string;
	onChange?: (value: string) => void;
}

export function UploadBox({ placeholder, value, onChange, ...other }: Props) {
	const customRequest = async (options: any) => {
		const { file, onSuccess, onError } = options;
		try {
			const data = await commonService.uploadFile(file);
			onSuccess();
			onChange?.(data.url);
		} catch (error) {
			message.error("上传失败");
			onError();
		}
	};

	return (
		<GlobalStyle>
			<StyledUploadBox>
				<Dragger
					{...other}
					customRequest={customRequest}
					showUploadList={false}
				>
					{value ? (
						<div className="preview-wrapper">
							<Image
								src={value}
								alt="上传预览"
								className="preview-image"
								onClick={(e) => e.stopPropagation()}
							/>
							<div 
								className="delete-icon" 
								onClick={(e) => {
									e.stopPropagation();
									onChange?.("");
								}}
							>
								<Iconify icon="material-symbols:delete-outline" />
							</div>
						</div>
					) : (
						placeholder || (
							<div className="upload-placeholder">
								<Iconify icon="material-symbols:cloud-upload" />
								<div className="ant-upload-text">
									点击或拖拽文件上传
								</div>
							</div>
						)
					)}
				</Dragger>
			</StyledUploadBox>
		</GlobalStyle>
	);
}
